package org.fireflow2.designer.eclipse.properties.tab;

import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.views.properties.tabbed.AbstractPropertySection;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import org.fireflow2.designer.eclipse.modelwrapper.AbsWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.ActivityWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.TransitionWrapper;

public class TransitionAttributePropertySection extends AbstractPropertySection {
	AbstractEditPart editPart = null;
	AbsWrapper modelWrapper = null;
	Text conditionText = null;
	public void createControls(Composite parent,
			TabbedPropertySheetPage aTabbedPropertySheetPage) {
		super.createControls(parent, aTabbedPropertySheetPage);

		Composite composite = getWidgetFactory()
				.createFlatFormComposite(parent);

		composite.setLayout(new GridLayout(2, false));
		
		// CompleteStrategy
		getWidgetFactory().createCLabel(composite, "Condition: ");
		
		conditionText  = this.getWidgetFactory().createText(composite, "");
		conditionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		conditionText.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent arg0) {
				// TODO Auto-generated method stub

			}

			public void focusLost(FocusEvent arg0) {
				// TODO Auto-generated method stub
				String oldValue = ((TransitionWrapper)modelWrapper).getCondition();
				if (oldValue==null) oldValue="";
				String newValue = conditionText.getText();
				if (newValue==null) newValue="";
				if (oldValue.trim().equals(newValue.trim()))return;
				
				((TransitionWrapper)modelWrapper).setCondition(newValue.trim());
			}

		});
	}
	
	@Override
	public void refresh() {
		super.refresh();
		String s = ((TransitionWrapper)modelWrapper).getCondition();
		if(s!=null && !s.trim().equals("")){
			conditionText.setText(s);
		}else{
			conditionText.setText("");
		}
	}
	
	@Override
	public void setInput(IWorkbenchPart part, ISelection selection) {
		super.setInput(part, selection);
		Object obj = ((IStructuredSelection) selection).getFirstElement();
		if (obj instanceof AbstractEditPart) {
			editPart = (AbstractEditPart) obj;
			modelWrapper = (AbsWrapper) editPart.getModel();
		}
	}	
}
